<template>
  <div class="login-container">
    <div class="login-card">
      <div class="login-header">
        <div class="logo">
          <img src="/exam-ai-logo.svg" alt="Exam AI" class="logo-img">
          <h1 class="logo-text">Exam AI</h1>
        </div>
        <p class="subtitle">智能考试系统</p>
      </div>

      <form @submit.prevent="handleLogin" class="login-form">
        <div class="form-group">
          <label for="username" class="form-label">用户名</label>
          <div class="input-wrapper">
            <i class="icon user-icon">👤</i>
            <input id="username" v-model="form.username" type="text" placeholder="请输入用户名" required :disabled="loading"
              class="form-input">
          </div>
        </div>

        <div class="form-group">
          <label for="password" class="form-label">密码</label>
          <div class="input-wrapper">
            <i class="icon lock-icon">🔒</i>
            <input id="password" v-model="form.password" :type="showPassword ? 'text' : 'password'" placeholder="请输入密码"
              required :disabled="loading" class="form-input">
            <button type="button" @click="togglePassword" class="password-toggle" :disabled="loading">
              {{ showPassword ? '👁️' : '👁️‍🗨️' }}
            </button>
          </div>
        </div>

        <div v-if="error" class="error-message">
          <i class="error-icon">⚠️</i>
          {{ error }}
        </div>

        <button type="submit" :disabled="loading || !form.username || !form.password" class="login-button">
          <span v-if="loading" class="loading-spinner"></span>
          {{ loading ? '登录中...' : '登录' }}
        </button>
      </form>

      <div class="login-footer">
        <p class="register-link">
          还没有账号？<router-link to="/register" class="link">立即注册</router-link>
        </p>

        <div class="test-accounts">
          <h4>测试账号</h4>
          <div class="account-list">
            <div class="account-item">
              <span class="role admin">管理员</span>
              <span class="credentials">admin / 123456</span>
            </div>
            <div class="account-item">
              <span class="role teacher">教师</span>
              <span class="credentials">teacher / 123456</span>
            </div>
            <div class="account-item">
              <span class="role student">学生</span>
              <span class="credentials">student / 123456</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useAuthStore } from '@/stores/auth'
import { useRouter } from 'vue-router'
import authApi from '@/api/auth'
import '@/styles/auth/login.css'

const authStore = useAuthStore()
const router = useRouter()

const form = reactive({
  username: '',
  password: ''
})

const loading = ref(false)
const error = ref('')
const showPassword = ref(false)

const togglePassword = () => {
  showPassword.value = !showPassword.value
}

const handleLogin = async () => {
  if (loading.value) return

  loading.value = true
  error.value = ''

  try {
    const response = await authApi.login({
      username: form.username,
      password: form.password
    })

    // 后端返回的是 ResultVO 格式，需要从 data 字段获取实际数据
    const { data } = response.data

    // 检查响应数据是否存在
    if (!data || !data.token || !data.user) {
      throw new Error('登录响应数据不完整')
    }

    const { user, token } = data

    console.log('登录成功，用户信息:', user)
    console.log('用户角色:', user.role)

    await authStore.login({
      user,
      token
    })

    // 根据用户角色跳转到不同页面
    const role = user.role
    console.log('准备跳转，角色:', role)

    if (role === 'ADMIN') {
      console.log('跳转到管理员页面')
      router.push('/admin')
    } else if (role === 'TEACHER') {
      console.log('跳转到教师页面')
      router.push('/teacher')
    } else {
      console.log('跳转到学生页面')
      router.push('/student')
    }

  } catch (err) {
    console.error('登录失败:', err)
    // 处理后端返回的错误信息
    if (err.response?.data?.message) {
      error.value = err.response.data.message
    } else if (err.message) {
      error.value = err.message
    } else {
      error.value = '登录失败，请检查用户名和密码'
    }
  } finally {
    loading.value = false
  }
}
</script>
